<template>
  <el-row>
    <el-col :span="24" v-for="(order ,index) in orders" :key="index" id="el-div-1" class="order-container">
      <el-container class="order-card">
        <el-header>
          <div class="grid-content ep-bg-purple-dark"  >
            <div style="color: skyblue" class="div-h1">订单号: {{order.id}}

            </div>
          </div>
        </el-header>
        <el-main>
          <el-row type="flex" justify="start">
            <span class="span-h1">下单菜品:</span>
            <el-col :span="4" v-for="(item, index) in order.items.slice(0, 4)" :key="index">
              <el-image
                  style="width: 50%; height: auto"
                  :src="item.imageUrl"
                  :fit="fit"
              />

            </el-col>
            <span>订单状态:{{order.status}}</span>
          </el-row>
        </el-main>

        <el-footer>
          <div><span class=" span-h2">下单时间: {{order.ordertime}}</span></div>
          <el-button type="danger" v-show="order.deleteapply" @click="changeorderId(order)">退款</el-button>
          <el-button type="danger" v-show="order.delete" @click="changeorderId(order)">取消支付</el-button>
          <el-button type="primary" v-show="order.isshowbuttonsee" @click="searchRouter(order)">查看订单</el-button>
          <el-button type="warning"  v-show="order.isshowbuttonapply" @click="alipayordertest(subject,order,orderno)">支付订单</el-button>
        </el-footer>

      </el-container>
    </el-col>
  </el-row>
  <el-dialog
      v-model="centerDialogVisible"
      title="Warning"
      width="500"
      align-center
  >
    <span>如果确认退款,则该订单将取消,请谨慎操作</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="deletorderandorderdetailByorderId(orders)">
          确认退款
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {h, nextTick, onMounted, onUnmounted, reactive, ref, watch} from "vue";
import {
  deletorderandorderdeTaliByorderIDservice,
  findorderstatusByuseridservice,
  getaplyedorderdetaiservice,
  getitemlistbyorderIdservice
} from "@/api/food.js";
import {useRouter} from "vue-router";
import {ElNotification} from "element-plus";
const centerDialogVisible=ref(false);
const orderId= ref(1);
const orders=reactive([])
const items=reactive([])
const isshowbuttonapply=ref(false)
const isshowbuttonsee=ref(false)
const subject=ref('顾客')
const orderno=ref(1);
const routers=useRouter();
const dialogVisible = ref(false);
const status=ref('正在下单')
const fitorderId=ref(1);
const handleCommentClick = () => {
  dialogVisible.value = true;

};
const changeorderId = (order) => {
  centerDialogVisible.value = true
  fitorderId.value=order.id
  console.log(fitorderId.value)
}
const handleCancel=()=>{

  dialogVisible.value = false;
}

const findorder = async () => {
  const response = await findorderstatusByuseridservice();

  if (response.code === 200) {
    const orderPromises = response.date.map(async order => {
      await getitemlistbyorderId(order);
      return order; // 确保每个order对象都包含了items后再返回
    });

    // 等待所有getitemlistbyorderId操作完成
    const updatedOrders = await Promise.all(orderPromises);
    orders.splice(0, orders.length, ...updatedOrders); // 清空并添加新数据
    console.log(orders);
    comfirmstatus(orders);
  } else {
    console.log("获取订单失败");
    console.log(response.message);
  }
};


const getitemlistbyorderId = async (order) => {
const response=await getitemlistbyorderIdservice(order.id)
  if(response.code ===200){
    console.log(response.date)
    order.items = response.date;
    order.deleteapply=false
    order.isshowbuttonapply=false
    order.isshowbuttonsee=false
    order.delete=false
    order.ordertime=formatDateTime(order.ordertime);
  }
  else {
    console.log("获取订单失败")
    console.log(response.message)
  }
}
const formatDateTime = (dateTimeStr) => {
  const date = new Date(dateTimeStr);
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
};
onMounted( () => {
   findorder()
  generateOrderNumber()

})
const deletorderandorderdetailByorderId = async (orders) => {
  for (const order of orders) {
    if(order.id===fitorderId.value){
      const response = await deletorderandorderdeTaliByorderIDservice(order.id)
      if(response.code ===200){
        centerDialogVisible.value = false
      await findorder()
        ElNotification({
          title: 'Title',
          message: h('i', { style: 'color: teal' }, '取消订单成功'),
        })
        console.log(response.message)
      }
      else {
        console.log(response.message)
      }

    }


  }

}
const comfirmstatus = (orders) => {
  orders.forEach(order => {
    if(order.status.includes('正在下单')){
      order.deleteapply=false
      order.delete=false
      order.isshowbuttonapply=false
      order.isshowbuttonsee=false
    }
    if(order.status.includes('等待支付')){
      order.deleteapply=false
      order.delete=true
      order.isshowbuttonapply=true
      order.isshowbuttonsee=false
    }
    if(order.status.includes('完成支付')){
      order.deleteapply=true
      order.delete=false
      order.isshowbuttonsee=true
      order.isshowbuttonapply=false
   order.status='完成支付'
    }
    if(order.status.includes('正在制作')){
      order.deleteapply=false
      order.delete=false
      order.isshowbuttonsee=true
      order.isshowbuttonapply=false
      order.status='正在制作'
    }
    if( order.status.includes('正在配送')){
      order.deleteapply=false
      order.delete=false
      order.isshowbuttonsee=true
      order.isshowbuttonapply=false
       order.status='正在配送'
    }
    if( order.status.includes('订单已完成')){
      order.deleteapply=false
      order.delete=false
      order.isshowbuttonsee=true
      order.isshowbuttonapply=false
      order.status='订单已完成'
    }
    if(order.status.includes('已退款')){
      order.status='已退款'
    }
})

}
const generateOrderNumber=()=> {
  const timestamp = Date.now().toString(); // 当前时间戳
  const randomNum = Math.floor(Math.random() * 100000).toString().padStart(5, '0'); // 5位随机数
  const orderNumber = parseInt(`${timestamp}${randomNum.toString().padStart(5, '0')}`);
  orderno.value= orderNumber; // 将生成的订单号赋值给 traceNo
}
const alipayordertest=async (subject,order,orderno)=>{
  await alipayorder(subject,order,orderno)
}
const alipayorder=  (subject,order,orderno)=>{
   const params =  new URLSearchParams({
    subject: subject,
    traceNo: orderno,
    totalAmount: order.totalamount,
  });
 window.location.href = `http://lsyspringboot.natapp1.cc/alipay/pay?${params.toString()}`;
}

const searchRouter=async (order)=>{
  await routers.push({
    path:'/orderfood/orderedselect',
    query: {
      orderId:order.id,
    }
  })
}
</script>


<style scoped>
.order-container {
  overflow: hidden; /* 防止阴影溢出 */
}

.order-card {
  background-color: #ffffff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  margin-bottom: 20px;
  position: relative; /* 为了悬浮效果 */
  z-index: 1; /* 保证卡片在其他元素之上 */
  padding: 20px;
  transition: box-shadow 0.3s ease;
}

.order-card:hover {
  box-shadow: 0 8px 12px rgba(0, 0, 0, 0.15);
}

.el-header, .el-footer {
  padding: 10px 20px;
  color: #fff;
  text-align: center;
  background-color: #3f51b5; /* 更改颜色以匹配卡片主题 */
  border-radius: 8px 8px 0 0; /* 匹配卡片边框 */
}

.el-footer {
  background-color: #f5f5f5; /* 更改为浅色背景以区分头部 */
  border-radius: 0 0 8px 8px;
}

.div-h1 {
  margin-bottom: 10px;
}

.span-h1 {
  margin-right: 20px;
}
.span-h2{
  font-size: large;
  font-family: 隶书;
  color: black;
}


</style>